// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/runner/multi_fragment_plan.h>

namespace kumo::pollux::runner {
    namespace {
        std::string toFragmentsString(
            const std::vector<ExecutableFragment> &fragments,
            const std::function<std::string(const core::PlanNode &)> &planNodeToString) {
            std::stringstream out;
            for (auto i = 0; i < fragments.size(); ++i) {
                const auto &fragment = fragments[i];
                out << fmt::format(
                            "Fragment {}: {} numWorkers={}:",
                            i,
                            fragment.taskPrefix,
                            fragment.width)
                        << std::endl;
                out << planNodeToString(*fragment.fragment.planNode) << std::endl;
                if (!fragment.inputStages.empty()) {
                    out << "Inputs: ";
                    for (auto &input: fragment.inputStages) {
                        out << fmt::format(
                            " {} <- {} ", input.consumerNodeId, input.producerTaskPrefix);
                    }
                    out << std::endl;
                }
            }
            return out.str();
        }
    } // namespace

    std::string MultiFragmentPlan::toString(bool detailed) const {
        return toFragmentsString(fragments_, [&](const auto &planNode) {
            return planNode.toString(detailed, true);
        });
    }

    std::string MultiFragmentPlan::to_summary_string(
        core::PlanSummaryOptions options) const {
        return toFragmentsString(fragments_, [&](const auto &planNode) {
            return planNode.to_summary_string(options);
        });
    }
} // namespace kumo::pollux::runner
